package DataStructureAndAlgorithm.CSP.Day01;

import java.util.Scanner;
public class AcWing_1396 {
    static int N = 55;
    static char[][] g = new char[N][N];
    static boolean[][] st1 = new boolean[N][N];
    static boolean[][] st2 = new boolean[N][N];
    static int[] dx =  {-1,0,1,0};
    static int[] dy =  {0,1,0,-1};
    static int n,m;
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        m = in.nextInt();
        for (int i = 0; i < n; i++){
            String temp = in.next();
            for (int j = 0; j < temp.length(); j++){
                g[i][j] = temp.charAt(j);
            }
        }
        int tx = 0,ty = 0;
        //找出起点和终点，并分别总起点和终点开始深搜遍历，最后，将所有从起点出发能到达，而从终点出发不能到达的点，即为所求
        for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++){
                if (g[i][j] == 'S'){
                    dfs1(i,j);
                }else if (g[i][j] == 'T'){
                    tx = i;
                    ty = j;
                    dfs2(i,j);
                }
            }
        }
        if (!st1[tx][ty]){
            System.out.print("I'm stuck!");
        }else {
            int res = 0;
            for (int i = 0; i < n; i++){
                for (int j = 0; j < m; j++){
                    //起点能到，终点不能到
                    if (st1[i][j] && !st2[i][j]){
                        res++;
                    }
                }
            }
            System.out.print(res);
        }

    }
    //深搜从起点出发，能到达的点，并把响应的点的标准设为true
    static void dfs1 (int x,int y){
        st1[x][y] = true;
        for (int i = 0; i < 4; i++){
            int a = x + dx[i];
            int b = y + dy[i];
            //判断是否越界或者是否当前点不能再移动了
            if (a < 0 || a >= n || b < 0 || b >= m || g[a][b] == '#'){
                continue;
            }
            //判断该点是否已经走过
            if (st1[a][b]){
                continue;
            }
            //检查该点附近的点能到走
            if (check(x,y,i)){
                dfs1(a,b);
            }
        }
    }
    static void dfs2 (int x,int y){
        st2[x][y] = true;
        for (int i = 0; i < 4; i++){
            int a = x + dx[i];
            int b = y + dy[i];
            //判断是否越界或者是否当前点不能再移动了
            if (a < 0 || a >= n || b < 0 || b >= m || g[a][b] == '#'){
                continue;
            }
            //判断该点是否已经走过
            if (st2[a][b]){
                continue;
            }
            //检查该点附近的点能到走
            if (check(a,b,i ^ 2)){
                dfs2(a,b);
            }
        }
    }
    static boolean check(int x,int y,int k){
        char c = g[x][y];
        if (c == '+' || c == 'S' || c == 'T')return true;
        if (c == '-' && k % 2 == 1)return true;
        if (c == '|' && k % 2 == 0)return true;
        if (c == '.' && k == 2)return true;
        return false;
    }
}
